#!/usr/bin/env python3
"""
libtommath MCP Server

面向 libtommath 数学库的 MCP 服务器，提供命令行工具来测试库的编译和运行功能。

MCP tools 列表：
1. libtommath_compile_example - 编译使用 libtommath 库的 C 程序
   参数：source_code (str): C 源代码内容, output_name (str): 输出可执行文件名
   返回：{"success": bool, "command": str, "exit_code": int, "stdout": str, "stderr": str}

2. libtommath_run_example - 运行已编译的 libtommath 示例程序
   参数：executable_path (str): 可执行文件路径
   返回：{"success": bool, "command": str, "exit_code": int, "stdout": str, "stderr": str}
"""

import subprocess
import tempfile
import os
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("libtommath MCP Server")

@mcp.tool()
def libtommath_compile_example(source_code: str, output_name: str = "example") -> dict:
    """
    编译使用 libtommath 库的 C 程序示例
    
    参数:
        source_code: C 源代码内容
        output_name: 输出的可执行文件名
        
    返回:
        JSON 结构: {
            "success": 是否成功,
            "command": 执行的命令,
            "exit_code": 退出码,
            "stdout": 标准输出,
            "stderr": 标准错误
        }
    """
    try:
        # 创建临时文件保存源代码
        with tempfile.NamedTemporaryFile(mode='w', suffix='.c', delete=False) as f:
            f.write(source_code)
            source_file = f.name
        
        # 编译命令
        command = ["gcc", source_file, "-o", output_name, "-ltommath"]
        result = subprocess.run(command, capture_output=True, text=True)
        
        # 清理临时文件
        os.unlink(source_file)
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(command),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
        
    except Exception as e:
        return {
            "success": False,
            "command": f"gcc compilation with libtommath",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def libtommath_run_example(executable_path: str) -> dict:
    """
    运行已编译的 libtommath 示例程序
    
    参数:
        executable_path: 可执行文件的路径
        
    返回:
        JSON 结构: {
            "success": 是否成功,
            "command": 执行的命令,
            "exit_code": 退出码,
            "stdout": 标准输出,
            "stderr": 标准错误
        }
    """
    try:
        # 检查文件是否存在
        if not os.path.exists(executable_path):
            return {
                "success": False,
                "command": f"run {executable_path}",
                "exit_code": -1,
                "stdout": "",
                "stderr": f"Executable file not found: {executable_path}"
            }
        
        # 运行可执行文件
        command = [executable_path]
        result = subprocess.run(command, capture_output=True, text=True)
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(command),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
        
    except Exception as e:
        return {
            "success": False,
            "command": f"run {executable_path}",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()